//
//  SRHomeworkAudioViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/9/19.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRHomeworkAudioViewController.h"

#import <MJRefresh/MJRefresh.h>
#import "SRHomeworkPictureModel.h"
#import "SRHomeworkPictureTableViewCell.h"
#import "SRHomeworkPictureHeaderView.h"
#import "SRSchoolClassServices.h"
#import "SRHomeworkAnswerModel.h"
#import "SRHomeworkDetailItemModel.h"

#import "FZMCCacheManager.h"
#import "SRAudioPlayerManager.h"
#import "UIButton+FZGreenButton.h"
#import "AudioRecord.h"
#import <SRUploadQiniuManager.h>
#import <lame/lame.h>

@interface SRHomeworkAudioViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) SRHomeworkPictureHeaderView *headerView;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) UIButton *rightButton;
@property (strong, nonatomic) UIButton *recordButton;

@property (strong, nonatomic) UIView *recordContentView;
@property (strong, nonatomic) UIImageView *recordPlayImageView;
@property (strong, nonatomic) UILabel *recordTimeLabel;


@property (strong, nonatomic) NSMutableArray *items;
@property (assign, nonatomic) NSInteger pageIndex;

@property (strong, nonatomic) SRHomeworkDetailItemModel *detialModel;
@property (strong, nonatomic) SRHomeworkPictureModel *currentItemModel;

@property (assign, nonatomic) CGFloat headerHeight;
@property (assign, nonatomic) BOOL isFinished;

@property (strong, nonatomic) AudioRecord *audioRecord;
@property (strong, nonatomic) NSString *cafPath;
@property (strong, nonatomic) NSString *mp3Path;
@property (strong, nonatomic) NSString *audioFileName;

@property (strong, nonatomic) UIActivityIndicatorView *activityView;

@end

@implementation SRHomeworkAudioViewController

- (void)doBack {
    
    if (self.isFinishedDetail) {
        [super doBack];
        return;
    }
    
    
    if (self.isFinished) {
        [super doBack];
    } else {
        WEAKSELF
        UIAlertView *alertView = [UIAlertView alertViewWithTitle:@"确认放弃" message:@"任务未完成，是否放弃？" cancelButtonTitle:@"取消" didDismissBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        } otherButtonTitles:@"确定", nil];
        
        [alertView show];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    
    [self setupData];
    [self setupView];
    
        //    [self showLoadingViewWithCompletedBlock:nil];
    [self startProgressHUD];
    
    if (self.isFinishedDetail) {
        [self queryDataFinishDetail];
        self.tableView.allowsSelection = NO;
        
        self.recordButton.hidden = YES;
        
    } else {
        [self queryData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self updateHeaderViewHeight];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];
    
}

- (void)updateHeaderViewHeight {
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.headerHeight);
    
}

#pragma mark - setup

- (void)setupData {
    self.pageIndex = 0;
    self.items = [@[] mutableCopy];
}

- (void)setupView {
    
    WEAKSELF
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 154;
    
    [self.tableView registerNib:[UINib nibWithNibName:kSRHomeworkPictureTableViewCell bundle:nil] forCellReuseIdentifier:kSRHomeworkPictureTableViewCell];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.top.equalTo(self.view);
    }];
    self.view.backgroundColor = self.tableView.backgroundColor = css.color_2;
    
    self.audioRecord = [[AudioRecord alloc] initFromViewController:self];
    self.audioRecord.completeBlock = ^(BOOL finished, NSURL *audioFilePath) {
        if (finished) {
                //结束录音
            weakSelf.cafPath = [weakSelf.audioRecord.tmpFileUrl path];
            weakSelf.mp3Path = [FZMCCacheManager recordMp3FilePathWithProblemID:weakSelf.currentItemModel.problem_id];
            NSError *error = nil;
            [[NSFileManager defaultManager] copyItemAtPath:weakSelf.cafPath toPath:weakSelf.mp3Path error:&error];
            if (error) {
                NSLog(@"file copy error:%@", error);
            }
            
			weakSelf.audioFileName = [NSString stringWithFormat:@"hwRecord_%lld.aac", (long long)[[NSDate date] timeIntervalSince1970]];

                //            [weakSelf covertCaf:weakSelf.cafPath toMp3:weakSelf.mp3Path];
            
            weakSelf.recordContentView.hidden = NO;
            NSInteger timeStamp = [weakSelf.audioRecord timeLenght];
            if (timeStamp <= 60) {
				weakSelf.recordTimeLabel.text = [NSString stringWithFormat:@"%02ld秒", (long)timeStamp];
            } else {
				weakSelf.recordTimeLabel.text = [NSString stringWithFormat:@"%02ld分%02ld秒", timeStamp / 60, timeStamp % 60];
            }
            [weakSelf.tableView addSubview:weakSelf.recordContentView];
            weakSelf.recordContentView.frame = CGRectMake(SCREEN_WIDTH - 220, weakSelf.headerHeight + 30, 200, 44);
            
            [weakSelf convertMp3Success];
                //            weakSelf.recordButton.hidden = YES;
            
        } else {
                //时间太短，提示
            [weakSelf.audioRecord showTooShortSign];
        }
    };
    self.headerView = [[[NSBundle mainBundle] loadNibNamed:@"SRHomeworkPictureHeaderView" owner:nil options:nil] firstObject];
    self.headerHeight = 386;
    self.headerView.homeworkType = self.homeworkType;
    
    self.headerView.touchAudioBlock = ^{
        [weakSelf onTouchAudioPlayButton:nil];
    };
    
    self.headerView.didChangeDescHeightBlock = ^(CGFloat height) {
        weakSelf.headerHeight = 386 + height;
        [weakSelf updateHeaderViewHeight];
    };
    
    self.tableView.tableHeaderView = self.headerView;
    
    UIBarButtonItem *itemSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    itemSpacer.width = -10;
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rightButton setTitle:@"下一题" forState:UIControlStateNormal];
    self.rightButton.frame = CGRectMake(0, 0, 100/2., 90/2.);
    [self.rightButton setTitleColor:css.color_4 forState:UIControlStateNormal];
    [self.rightButton.titleLabel setFont:css.fontOfH5];
    [self.rightButton addTarget:self action:@selector(onRightButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    self.navigationItem.rightBarButtonItems = @[itemSpacer, rightItem];
    
    
    if (self.homeworkType == SRClassHomeworkTypeAudio) {
        self.recordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.recordButton applyGreenBackgroundColor];
        [self.recordButton setTitle:@"按住 说话" forState:UIControlStateNormal];
            //        [self.recordButton addTarget:self action:@selector(onTouchRecordButton:) forControlEvents:UIControlEventAllEvents];
        
        [self.recordButton addEventHandler:^(id sender, UIControlEvents controlEvent) {
            [weakSelf onTouchRecordButton:controlEvent];
            
        } forControlEvents:UIControlEventAllEvents];
        
        [self.view addSubview:self.recordButton];
        
        [self.recordButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.bottom.equalTo(self.view);
            make.height.mas_equalTo(45);
        }];
        
        self.recordContentView = [[UIView alloc] init];
        self.recordContentView.clipsToBounds = YES;
        self.recordContentView.layer.cornerRadius = 4;
        self.recordContentView.backgroundColor = [UIColor colorWithHex:0x10aa14];
        
        WEAKSELF
        [self.recordContentView addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
                //            if (weakSelf.touchAudioBlock) {
                //                weakSelf.touchAudioBlock();
                //            }
            [weakSelf onUserRecordPlayButton:nil];
        }];
        
        self.recordPlayImageView = [[UIImageView alloc] init];
        self.recordTimeLabel = [[UILabel alloc] init];
        self.recordTimeLabel.textAlignment = NSTextAlignmentLeft;
        
        self.recordPlayImageView.image = [UIImage imageNamed:@"voice02"];
        self.recordTimeLabel.textColor = [UIColor whiteColor];
        self.recordTimeLabel.font = css.fontOfH6;
        
        
        self.recordContentView.frame = CGRectMake(0, 0, 120, 44);
        [self.recordContentView addSubview:self.recordTimeLabel];
        [self.recordContentView addSubview:self.recordPlayImageView];
        
        [self.recordPlayImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.recordContentView).offset(10);
            make.centerY.equalTo(self.recordContentView);
            make.width.mas_equalTo(20);
            make.height.mas_equalTo(26);
        }];
        
        [self.recordTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.recordPlayImageView.mas_trailing).offset(5);
            make.centerY.equalTo(self.recordPlayImageView);
            make.height.mas_equalTo(20);
        }];
        
        self.activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        [self.recordContentView addSubview:self.activityView];
        
        [self.activityView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(self.recordContentView).offset( -20 - 50);
            make.centerY.equalTo(self.recordContentView);
            make.height.mas_equalTo(40);
            make.width.mas_equalTo(50);
        }];
        SRAudioPlayerManager *audioPlayer = [SRAudioPlayerManager sharedInstance];
        [audioPlayer setAudioFilePath:nil];
        [audioPlayer setAudioFileName:nil];
        
        audioPlayer.audioPlayerCompletedBlock = ^(BOOL finish) {
            [weakSelf.headerView setActivityAnimated:NO];
            [weakSelf.activityView stopAnimating];
        };
        
        audioPlayer.audioPlayerProgressBlock = ^(CGFloat progress) {
            if (progress > 0.2) {
                    //                [weakSelf.activityView stopAnimating];
            }
            
        };
        
        audioPlayer.audioRecorderFailureBlock = ^(NSString *message) {
            [weakSelf showHUDErrorMessage:message];
        };
        
    }
}


#pragma mark - Event

- (void)onUserRecordPlayButton:(id)sender {
    SRAudioPlayerManager *audioPlayer = [SRAudioPlayerManager sharedInstance];
    
    if (self.isFinishedDetail) {
        NSString *url = self.currentItemModel.answerByUser;
        
        if ([audioPlayer playingFileName] && [[audioPlayer playingFileName] isEqualToString:[url lastPathComponent]]) {
            if (audioPlayer.isPlaying) {
                [self.activityView stopAnimating];
                [audioPlayer pauseRecordAudio];
            } else {
                [self.activityView startAnimating];
                audioPlayer.audioFilePath = nil;
                [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFileURL:url];
                [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
                
            }
        }
        else {
            [self.activityView startAnimating];
            audioPlayer.audioFilePath = nil;
            
            [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFileURL:url];
            [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
            
        }
    } else {
        NSString *url = self.mp3Path;
        
        if ([audioPlayer playingFileName] && [[audioPlayer playingFileName] isEqualToString:[url lastPathComponent]]) {
            if (audioPlayer.isPlaying) {
                [self.activityView stopAnimating];
                [audioPlayer pauseRecordAudio];
            } else {
                [self.activityView startAnimating];
                [audioPlayer startPlayRecordAudio];
            }
        }
        else {
            [self.activityView startAnimating];
            [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFilePath:url];
            [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
            
        }
    }
}

- (void)onTouchRecordButton:(UIControlEvents)touchEvent {
    [self.activityView stopAnimating];
    [self.headerView setActivityAnimated:NO];
    [[SRAudioPlayerManager sharedInstance] pauseRecordAudio];
    
    if (UIControlEventTouchDown == touchEvent) {
        [self.audioRecord recordBegin];
    } else if (UIControlEventTouchDragInside == touchEvent ||
               UIControlEventTouchDragEnter == touchEvent) {
        self.audioRecord.voiceRecordView.state = LCChatRecorderMetersAlertViewStateRecording;
    } else if (UIControlEventTouchDragOutside == touchEvent ||
               UIControlEventTouchDragExit == touchEvent) {
        [self.audioRecord removeMicIconAndAddDeleteIcon];
    } else if (UIControlEventTouchUpInside == touchEvent) {
        [self.audioRecord recordComplete];
    } else if (UIControlEventTouchUpOutside == touchEvent ||
               UIControlEventTouchCancel == touchEvent) {
        [self.audioRecord recordCancel];
    }
    
}

- (void)onTouchAudioPlayButton:(id)sender {
    
    SRAudioPlayerManager *audioPlayer = [SRAudioPlayerManager sharedInstance];
    NSString *url = self.currentItemModel.audio;
    
    if ([audioPlayer playingFileName] && [[audioPlayer playingFileName] isEqualToString:[url lastPathComponent]]) {
        if (audioPlayer.isPlaying) {
            [self.headerView setActivityAnimated:NO];
            [audioPlayer pauseRecordAudio];
        } else {
            [self.headerView setActivityAnimated:YES];
            [audioPlayer startPlayRecordAudio];
        }
    }
    else {
        [self.headerView setActivityAnimated:YES];
        [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFileURL:url];
        [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
        
    }
}

- (void)onRightButtonClickAction:(id)sender {
    
    if (self.currentItemModel.index == ([self.detialModel.problems count]-1) ) {
        
        if (self.isFinishedDetail) {
                //完成返回；
            UIViewController *destVC = nil;
            for (UIViewController *vc in self.navigationController.viewControllers) {
                if ([vc isKindOfClass:NSClassFromString(@"SRClassHomeWorkDetailViewController")]) {
                    destVC = vc;
                    break;
                }
            }
            
            if (destVC) {
                [self.navigationController popToViewController:destVC animated:YES];
            } else {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            
            return;
        }
            //若当前是最后一题，则提交
        NSMutableDictionary *answerDict = [NSMutableDictionary dictionaryWithCapacity:4];
        for (SRHomeworkPictureModel *item in self.detialModel.problems) {
            [answerDict setValue:item.answerByUser forKey:item.problem_id];
        }
        
        if ([[answerDict allKeys] count] <= 0) {
            [self showHUDHintWithText:@"你还没有选择答案，请选择后再提交。"];
            return;
        }
        
        [self startProgressHUDWithText:@"提交中..."];
        
        self.isFinished = YES;
        
        NSError *error;
        NSString *answer = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:answerDict options:NSJSONWritingPrettyPrinted error:&error];
        if (! jsonData) {
                //转化失败
        } else {
            answer = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
        
        WEAKSELF
        [SRSchoolClassServices submitProblemAnswerWithTaskID:self.taskID groupID:self.detialModel.group_id answer:answer SuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
            [weakSelf stopProgressHUD];
            if (statusCode == kFZRequestStatusCodeSuccess) {
                [weakSelf showHUDHintWithText:@"提交成功"];
                [weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:1];
                
            } else {
                [weakSelf showHUDHintWithText:message];
            }
        } failureBlock:^(id responseObject, NSError *error) {
            [weakSelf stopProgressHUD];
            [weakSelf showHUDError];
        }];
        
        
    } else{
            //下一题
        if (self.currentItemModel.index < [self.detialModel.problems count]) {
            self.currentItemModel = self.detialModel.problems[self.currentItemModel.index + 1];
            [self.headerView updateQuestionInfo:self.currentItemModel];
            [self updateRightButtonTitle];
            
            if (self.homeworkType == SRClassHomeworkTypePicture) {
                [self.items removeAllObjects];
                [self.items addObjectsFromArray:self.currentItemModel.answerArray];
                
                [self.tableView reloadData];
            } else {
                if (self.isFinishedDetail) {
                    self.recordButton.hidden = YES;
                    self.recordContentView.hidden = NO;
                } else {
                    self.recordContentView.hidden = YES;
                    self.recordButton.hidden = NO;
                }
            }
            
            
            
            if (self.isFinishedDetail) {
                [self showUserRecordView];
            } else {
                if (self.currentItemModel.audio && [self.currentItemModel.audio length] > 0) {
                    [self onTouchAudioPlayButton:nil];
                }
            }
        }
    }
}

#pragma mark - Covert to Mp3

- (void)covertCaf:(NSString *)cafFilePath toMp3:(NSString *)mp3FilePath {
    @try {
        int read, write;
        
        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source
        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 44100);
            //                    lame_set_in_samplerate(lame, 11025.0 * 2);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
        [self performSelectorOnMainThread:@selector(convertMp3Failure)
                               withObject:nil
                            waitUntilDone:YES];
    }
    @finally {
        [self performSelectorOnMainThread:@selector(convertMp3Success)
                               withObject:nil
                            waitUntilDone:YES];
    }
}

- (void)convertMp3Failure {
    [self stopProgressHUD];
    
    NSString *message = [NSString stringWithFormat:@"录音转化为mp3 失败"];
    [self showHUDErrorMessage:message];
}

- (void)convertMp3Success {
    [self stopProgressHUD];
        //开始上传进度条
    [self updateHUDgrogress:MBProgressHUDModeDeterminate labelText:@"上传录音..."];
    WEAKSELF
        //上传图片到七牛云端
    [[SRUploadQiniuManager sharedInstance] uploadFileToQiNiuForPath:self.mp3Path key:self.audioFileName uploadToken:[SRLoginUser uploadToken] UploadPercent:^(NSString *key, float percent) {
        CGFloat progress = MIN(percent, 1.0);
        [weakSelf updateMyProgressTask:progress];
        
    } responseBlock:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        [weakSelf stopProgressHUD];
        
        if (info.isOK) {
                //上传成功
            weakSelf.currentItemModel.answerByUser = key;
            
        } else {
                //上传数据失败
            [weakSelf.recordButton setHidden:NO];
            
            NSString *message = [NSString stringWithFormat:@"录音上传失败ErrorCode(%d):%@", info.statusCode, resp];
            
            if (info.statusCode == 401) {
                    //token失效过期，提示重新登录
                message = [NSString stringWithFormat:@"认证过期，请重新登录\n录音上传失败ErrorCode(%d):%@", info.statusCode, resp];
                [weakSelf showHUDErrorMessage:message];
                
                [weakSelf performSelector:@selector(showLoginViewController) withObject:nil afterDelay:1];
                
            } else {
                [weakSelf showHUDErrorMessage:message];
                
            }
        }
    }];
}

- (void)showLoginViewController {
    [[SRLoginManager sharedManager] logout];
    [[SRLoginManager sharedManager] showLoginViewSinceController:self];
}

#pragma mark - Query Data


- (void)queryData{
    WEAKSELF
    [SRSchoolClassServices queryProblemDetailWithTaskID:self.taskID SuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
            //            [weakSelf.tableView.footer endRefreshing];
        
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
            weakSelf.detialModel = responseDataObject;
            
            [weakSelf parseQuestionModel:weakSelf.detialModel];
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
            //            [weakSelf.tableView.footer endRefreshing];
        [weakSelf stopProgressHUD];
        
    }];
    
}

- (void)queryDataFinishDetail{
    WEAKSELF
    [SRSchoolClassServices queryProblemFinishDetailWithFinishID:self.taskID SuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
            //            [weakSelf.tableView.footer endRefreshing];
        
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
            weakSelf.detialModel = responseDataObject;
            
            [weakSelf parseQuestionModel:weakSelf.detialModel];
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
            //            [weakSelf.tableView.footer endRefreshing];
        [weakSelf stopProgressHUD];
        
    }];
    
}

- (void)parseQuestionModel:(SRHomeworkDetailItemModel *)questionModel {
    if ([questionModel.problems count] > 0) {
        for (int i = 0; i < [questionModel.problems count]; ++ i) {
            SRHomeworkPictureModel *item = questionModel.problems[i];
            
            NSMutableArray *array = [NSMutableArray array];
            NSDictionary *answerDict = item.answer_pic;
            
            [answerDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                SRHomeworkAnswerModel *answerModel = [[SRHomeworkAnswerModel alloc] init];
                answerModel.problem_id = item.problem_id;
                answerModel.key = key;
                answerModel.pic = obj;
                
                [array addObject:answerModel];
            }];
            [array sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                SRHomeworkAnswerModel *item1 = obj1;
                SRHomeworkAnswerModel *item2 = obj2;
                return [item1.key compare:item2.key options:NSCaseInsensitiveSearch];
                
            }];
            
            item.answerArray = array;
            
            item.index = i;
        }
        
        self.title = questionModel.title;
        
        self.currentItemModel = [questionModel.problems firstObject];
        
        [self.headerView updateHeaderInfo:self.detialModel];
        [self.headerView updateQuestionInfo:self.currentItemModel];
        [self updateRightButtonTitle];
        
        [self.items removeAllObjects];
        [self.items addObjectsFromArray:self.currentItemModel.answerArray];
        
        [self.tableView reloadData];
        
        
        
        if (self.isFinishedDetail) {
            [self showUserRecordView];
        } else {
            if (self.currentItemModel.audio && [self.currentItemModel.audio length] > 0) {
                [self onTouchAudioPlayButton:nil];
            }
        }
        
    }
}

- (void)showUserRecordView {
    
    if (self.currentItemModel.answerByUser && [self.currentItemModel.answerByUser length] > 0) {
        NSInteger timeStamp = [self.currentItemModel.audio_timelen integerValue];
        if (timeStamp <= 60) {
            self.recordTimeLabel.text = [NSString stringWithFormat:@"%02lld秒", timeStamp];
        } else {
            self.recordTimeLabel.text = [NSString stringWithFormat:@"%02lld分%02lld秒", timeStamp / 60, timeStamp % 60];
        }
        [self.tableView addSubview:self.recordContentView];
        self.recordContentView.frame = CGRectMake(SCREEN_WIDTH - 220, self.headerHeight + 30, 200, 44);
    } else {
        self.recordContentView.hidden = YES;
    }
    
}

- (void)updateRightButtonTitle {
    if (self.currentItemModel.index == ([self.detialModel.problems count]-1) ) {
            //最后一个问题，
        if (self.isFinishedDetail) {
            [self.rightButton setTitle:@"完成" forState:UIControlStateNormal];
        } else {
            [self.rightButton setTitle:@"提交" forState:UIControlStateNormal];
        }
    } else {
        [self.rightButton setTitle:@"下一题" forState:UIControlStateNormal];
    }
}


#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.homeworkType == SRClassHomeworkTypePicture) {
        return [self.items count];
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SRHomeworkPictureTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRHomeworkPictureTableViewCell forIndexPath:indexPath];
    
    SRHomeworkAnswerModel *item = self.items[indexPath.row];
    [cell updateCellInfo:item];
    
    if (self.isFinishedDetail) {
        cell.isFinishDetail = YES;
        
        if ([item.key isEqualToString:self.currentItemModel.answerByUser]) {
                //            [cell setSelected:YES];
            cell.selectView.hidden = NO;
                //            [cell.contentView bringSubviewToFront:cell.selectView];
                //            cell.selectView.backgroundColor =[UIColor redColor];
            
        } else {
                //            [cell setSelected:NO];
            cell.selectView.hidden = YES;
        }
    }
    
    
    return cell;
}


#pragma mark - UITableViewDelegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SRHomeworkAnswerModel *item = self.items[indexPath.row];
    self.currentItemModel.answerByUser = item.key;
    
    if ([self.currentItemModel.answer isEqualToString:item.key]) {
        [self showHUDHintWithText:@"太棒了，回答正确！！！" image:[UIImage imageNamed:@"right"]];
    } else {
        [self showHUDHintWithText:@"答错了，继续加油哦！！！" image:[UIImage imageNamed:@"worry"]];;
    }
    
}

@end

